import datetime
import json

import uvicorn
from fastapi import FastAPI, Request
import pandas as pd
import config_read
import weather_api
import place_api
import code_share

main_api = FastAPI()


@main_api.middleware('http')
async def request_record(req: Request, call_next):
    dic_req = dict(req.headers)
    # print(dic_req.keys())
    request_info = {
        "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),  # 请求时间
        "method": req.method,  # 请求方法（GET/POST等）
        "url": str(req.url),  # 请求URL
        "headers": {'host': dic_req['host'],
                    'referer': dic_req.get('referer',None)}
        ,  # 请求头（转为字典便于保存）

    }
    response = await call_next(req)
    log_line = json.dumps(request_info, ensure_ascii=False) + "\n"  # 转为JSON字符串，保留中文

    with open("request_log.txt", "a", encoding="utf-8") as f:
        f.write(log_line)
    return response


main_api.include_router(weather_api.weather_api, prefix='/weather', tags=['天气预报'])
main_api.include_router(place_api.place_api, prefix='/place', tags=['地址'])
main_api.include_router(code_share.share_api, prefix='/code_share', tags=['源码分享'])

if __name__ == '__main__':
    uvicorn.run('main:main_api',
                host='0.0.0.0',
                # host='localhost',
                port=8098
                )
